package com.chat.netty.handlercfg;


import com.chat.netty.util.SSLWebSocketClient;
import com.chat.netty.websocketserver.websocketHandler.WebsocketNettyRequestHandler;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.DecoderException;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.ssl.SslHandler;
import io.netty.handler.stream.ChunkedWriteHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.DefaultResourceLoader;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.net.ssl.*;

import java.io.FileInputStream;
import java.io.InputStream;

import java.security.KeyStore;

@Slf4j
@Component
public class NettyChildChannelHandler extends ChannelInitializer<SocketChannel>{

	@Resource(name = "websocketNettyServerHandler")
	private ChannelHandler webSocketServerHandler;
	@Resource(name = "websocketNettyRequestHandler")
	private WebsocketNettyRequestHandler websocketNettyRequestHandler;


	@Value("${server.ssl.key-store-password}")
	private String sslPassword;

	@Value("${netty.openssl}")
	private boolean openssl;


	@Override
	protected void initChannel(SocketChannel ch) throws Exception {
		if (openssl){
				SSLEngine sslEngine = getServerSslContext().createSSLEngine();
				sslEngine.setNeedClientAuth(false);
				sslEngine.setUseClientMode(false);
				SslHandler sslHandler = new SslHandler(sslEngine);
				ch.pipeline().addLast(sslHandler);
		}
		ch.pipeline().addLast("http-codec", new HttpServerCodec()); // HTTP编码解码器
		ch.pipeline().addLast("aggregator", new HttpObjectAggregator(65536)); // 把HTTP头、HTTP体拼成完整的HTTP请求
		ch.pipeline().addLast("http-chunked", new ChunkedWriteHandler()); // 方便大文件传输，不过实质上都是短的文本数据
		ch.pipeline().addLast("websocket-handler",webSocketServerHandler);
		ch.pipeline().addLast("http-handler",websocketNettyRequestHandler);
	}


	public SSLContext getServerSslContext() throws Exception {

		DefaultResourceLoader resourceLoader = new DefaultResourceLoader();
		org.springframework.core.io.Resource resource = resourceLoader.getResource("classpath:cers/mystore.jks");
		InputStream inputStream = resource.getInputStream();

		log.info("加载了密码: {}", sslPassword);

		char[] passArray = sslPassword.toCharArray();
		SSLContext sslContext = SSLContext.getInstance("TLSv1.2");
		KeyStore ks = KeyStore.getInstance("JKS");
		//加载keytool 生成的文件
		ks.load(inputStream, passArray);
		KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
		kmf.init(ks, passArray);
		sslContext.init(kmf.getKeyManagers(), null, null);
		inputStream.close();
		return sslContext;
	}



}
